package com.cloud2eye.base.util;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.List;

/**
 * Created by niefp on 2017/11/29.
 */
public abstract  class Cloud2EyeCommonService<M extends Cloud2EyeCommonMapper<T>,T extends Serializable> {

    @Autowired
    private M m;


    public T queryById(Object id){
        return this.m.selectByPrimaryKey(id);
    }

    public Page<T> pageQuery(T t,int pageNum,int pageSize,String orderBy){
        Page<T> page = PageHelper.startPage(pageNum,pageSize,orderBy);
        this.m.select(t);
        return page;
    }

    public T update(T t){
        this.m.updateByPrimaryKeySelective(t);
        return t;
    }
    public void deleteByList(List<T> list)
    {
        for (T t:list
             ) {
            this.m.deleteByPrimaryKey(t);
        }

    }
    public void deleteById(String id){
        for(String s:id.split(",")){
            this.m.deleteByPrimaryKey(s);
        }
    }
    public void deleteByIdInt(String id){
        for(String s:id.split(",")){
            this.m.deleteByPrimaryKey(Integer.parseInt(s));
        }
    }
//    public void deleteById(Object id){
//        this.m.deleteByPrimaryKey(id);
//    }
    public List<T> queryAll(T t){
        return this.m.select(t);
    }

    public T save(T t){
        this.m.insertSelective(t);
        return t;
    }
    public Page<T> pageQueryLike(T t,int pageNum,int pageSize,String orderBy){
        Page<T> page = PageHelper.startPage(pageNum,pageSize,orderBy);
            Example example = new Example(t.getClass());
            Example.Criteria criteria = example.createCriteria();
            Field[] fields = t.getClass().getDeclaredFields();
            for(Field f:fields){
                try {
                    f.setAccessible(true);
                    if(f.get(t)==null||"".equals(String.valueOf(f.get(t)))){
                        continue;
                    }
                    if(f.getType()==String.class) {
                        criteria.andLike(f.getName(),"%"+String.valueOf(f.get(t))+"%");
                    }else{
                        criteria.andEqualTo(f.getName(),f.get(t));
                    }

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            m.selectByExample(example);

        return page;
    }
}
